﻿using Microsoft.Extensions.ObjectPool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EssentialWebFramework.Library.ObjectPool
{
    public class SimpleRudeObjectPool<T> : DefaultObjectPool<T>
        where T : class
    {
        private SemaphoreSlim _semaphore;

        public SimpleRudeObjectPool(IPooledObjectPolicy<T> policy) : base(policy)
        {
            _semaphore = new SemaphoreSlim(Environment.ProcessorCount * 2);
        }

        public SimpleRudeObjectPool(IPooledObjectPolicy<T> policy, int maximumRetained) : base(policy, maximumRetained)
        {
            _semaphore = new SemaphoreSlim(maximumRetained);
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public override T Get()
        {
            _semaphore.Wait();
            return base.Get();
        }

        /// <summary>
        /// 归还
        /// </summary>
        /// <param name="obj"></param>
        public override void Return(T obj)
        {
            base.Return(obj);
            _semaphore.Release();
        }
    }
}
